package com.example.helllo;

import android.app.ListActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class FirstListActivity extends ListActivity implements Runnable {
    private static final String TAG = "FirstListActivity";
    Handler handler;
    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_first_list);

        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
        logDate = sp.getString(DATE_SP_KEY, "");
        Log.i("List", "lastRateDateStr=" + logDate);

        Thread t = new Thread(this);
        t.start();

        handler = new Handler() {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what ==8) {
                    //进行消息处理
                    //ArrayList<String> list2=(ArrayList<String>)msg.obj;

                    //ListAdapter adapter=new ArrayAdapter<String>(FirstListActivity.this, android.R.layout.simple_list_item_1,list2);
                    //setListAdapter(adapter);//设置数据适配器，把当前界面用adapter绑定
                    ArrayList<HashMap<String, String>> listItems = (ArrayList<HashMap<String, String>>) msg.obj;
                    SimpleAdapter listItemAdapter = new SimpleAdapter(FirstListActivity.this,
                            listItems,
                            R.layout.list_item,
                            new String[]{"Country", "Rate"},
                            new int[]{R.id.itemTitle, R.id.itemDetail}
                    );
                    MyAdapter adapter = new MyAdapter(FirstListActivity.this, R.layout.list_item, listItems);
                    setListAdapter(adapter);
                    //listView.setAdapter(listItemAdapter);
                    //setListAdapter(listItemAdapter);
                }
                super.handleMessage(msg);
            }
        };
//        MyTask task = new MyTask();
//        task.setHandler(handler);

    }


    @Override
    public void run() {

        Log.i(TAG, "run:......");
        List<String> ret = new ArrayList<String>();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i("run", "curDateStr:" + curDateStr + " logDate:" + logDate);
        if (curDateStr.equals(logDate)) {
            //如果相等，则不从网络中获取数据
            Log.i("run", "日期相等，从数据库中获取数据");
            RateManager manager = new RateManager(this);
            for(RateItem rateItem : manager.listAll()){
                ret.add(rateItem.getCurName() + "-->" + rateItem.getCurRate());
                Log.i(TAG, "run: rateItem=" + rateItem.getCurName());
            }
        } else {
            //从网络获取数据
            Log.i("run", "日期不相等，从网络中获取在线数据");
            Document doc =null;
            try {
                Thread.sleep(10);
                doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/index.html").get();
                Log.i(TAG, "title:" + doc.title());
                Element table = doc.getElementsByTag("table").get(1);
                Elements trs = table.getElementsByTag("tr");
                List<RateItem> rateList=new ArrayList<RateItem>();
                for (Element tr : trs) {
                    Elements tds = tr.getElementsByTag("td");
                    if (tds.size() > 0) {
                        String str = tds.get(0).text();
                        String val = tds.get(5).text();

                        Log.i(TAG, "run: td1=" + str + "==>" + val);
                        ret.add(str + "-->" + val);
                        rateList.add(new RateItem(str,val));
                    }
                    //把数据写入数据库
                    RateManager manager = new RateManager(this);
                    manager.deleteAll();
                    manager.addAll(rateList);
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }

                //更新记录日期
                SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString(DATE_SP_KEY, curDateStr);
                edit.commit();
                Log.i("run","更新日期结束：" + curDateStr);

                //返回消息到主线程

        }
        Message msg = handler.obtainMessage(8);
        msg.obj=ret;
        Log.i(TAG, "run: sendMessage");
        handler.sendMessage(msg);

    }
}